<template>
  <div id="page" style="padding:20px">
    <!-- 保存按钮 -->
    <div class="top-content">
      <h4 class="mb-5 mt-5">工艺名称:{{ routeQuery?.RouteCode + ' ' + routeQuery?.RouteName }}</h4>
      <div>
        <el-button type="info" @click="$router.go(-1)">返回</el-button>
        <el-button type="primary" @click="saveData">保存流程</el-button>
      </div>
    </div>
    <div style="display: flex;border:1px  #ebeef5;">
      <!-- 左侧可拖动元素 -->
      <div style="flex: 1; padding:10px; display: flex; flex-direction: column; height: 100%;">
        <!-- 表头（搜索框和标题） -->
        <div style="display: flex; align-items: center; margin-bottom: 10px; background: #f5f5f5; padding: 10px; border-bottom: 1px solid #ddd;">
          <span style="margin-right: 10px;">工序列表</span>
          <el-input v-model="searchQuery" @input="filterItems" placeholder="搜索工序" style="padding: 5px; width: 70%;" />
        </div>
        <!-- 列表（可滚动） -->
        <div class="list-container" style="width: 400px;">
          <div style="width: 100%; display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;">
            <div v-for="(item, index) in filteredItems" :key="index" class="draggable-item"
              :class="calCurItem(item) ? 'disabledItem' : ''" draggable="true" @dragstart="handleDragStart(item)"
              @dragend="handleDragEnd" style="text-align: center;">
              <el-tooltip
                :content="item.text"
                placement="bottom"
                effect="light"
              >
                {{ item.text.length > 10 ? item.text.slice(0, 10) + '...' : item.text }}
              </el-tooltip>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧画布 -->
      <div style="flex: 5; padding: 12px;border-right:2px solid #ebeef5;">
        <span class="mb-10">工序步骤（选择左侧工序进行拖拽排序）</span>
        <div class="canvas canvas-container" @drop="handleDrop" @dragover.prevent @click="handleClickCanvas" ref="canvas">
          <div v-for="(item, index) in canvasItems" :key="index" class="canvas-item"
            :class="index == 0 ? 'start' : index == canvasItems.length - 1 ? 'end' : ''" :data-index="index"
            :id="item.id" :style="{ position: 'relative' }" @click="clickDragItem(item, index)">
            <div>
              <span>
                <el-tooltip
                :content="item.text"
                placement="bottom"
                effect="light"
              >
                {{ item.text.length > 10 ? item.text.slice(0, 10) + '...' : item.text }}
              </el-tooltip>
              </span>

              <el-icon class="delBtn" @click.stop="delCur(index)">
                <CircleCloseFilled style="width:25px;height:25px" color="red" />
              </el-icon>

              <span v-if="index == 0 && canvasItems.length != 1" class="divText">开始</span>
              <span v-if="canvasItems.length - 1 == index && canvasItems.length != 1" class="divText">结束</span>
              <!-- 使用 div 元素创建连线 -->
              <div v-if="index != 0" :style="{
                width: '2px',
                height: '40px',
                background: 'black',
                position: 'absolute',
                top: `-55%`,
                left: `50%`,
                transform: `translate(-50%, -50%)`,

              }">
                <span class="arrow"></span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="topTitle mt-20" v-if="!!curDragItem.RouteControlId && false">
      <div class="top-title">{{ curDragItem.text}} 信息配置</div>
      <div >
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="设备信息维护" name="first">
            <div class="panel-body">
              <el-row :gutter="10" type="flex" style="font-size: 12px; margin-bottom: 15px">
                <el-col :span="5">
                  <label>设备</label>
                </el-col>
                <el-col :span="3">
                  <label>小时产量</label>
                </el-col>
                <el-col :span="3">
                  <label>产出节拍</label>
                </el-col>
                <el-col :span="3">
                  <label>前置时长</label>
                </el-col>
                <el-col :span="3">
                  <label>准备时长</label>
                </el-col>
                <el-col :span="3">
                  <label>后置时长</label>
                </el-col>
                <el-col :span="4">
                  <label>操作</label>
                </el-col>
              </el-row>
              <el-row :gutter="10" class="mb-10" type="flex" v-for="(d, i) in MachineInfo" :key="i">
                <el-col :span="5">
                  <el-select style="width: 100%" v-model="d.MachineId" filterable>
                    <el-option v-for="(i, t) in MachineOptions" :key="t" :label="`${i.MachineCode} ${i.MachineName} `"
                      :value="i.MachineId"></el-option>
                  </el-select>
                </el-col>
                <el-col :span="3">
                  <el-input-number v-model="d.Uph"></el-input-number>
                </el-col>
                <el-col :span="3">
                  <el-input-number v-model="d.OutputCircle"></el-input-number>
                </el-col>
                <el-col :span="3">
                  <el-input-number v-model="d.BeforeMinutes"></el-input-number>
                </el-col>
                <el-col :span="3">
                  <el-input-number v-model="d.PreparationMinutes"></el-input-number>
                </el-col>
                <el-col :span="3">
                  <el-input-number v-model="d.AfterMinutes"></el-input-number>
                </el-col>
                <el-col :span="4">
                  <div class="flex">
                    <a class="text-red t-18 mt-8" type="text" @click.prevent="deleteSite(d, i)" circle><i
                        class="el-icon-delete"></i></a>
                    <a class="text-blue t-18 ml-12 mt-8" type="text" @click.prevent="addSite"
                      v-if="i == MachineInfo.length - 1" circle><i class="el-icon-circle-plus-outline"></i></a>
                  </div>
                </el-col>
              </el-row>
            </div>
            <div class="fr">
              <el-button type="primary" @click="submit">保存设备信息</el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="物料信息" name="second">
            <div class="panel-body">
              <el-row :gutter="10" type="flex" style="font-size: 12px; margin-bottom: 15px">
                <el-col :span="4">
                  <label>产品</label>
                </el-col>
                <el-col :span="14" class="ml-20">
                  <label>所需物料</label>
                </el-col>
                <el-col :span="4">
                  <label>操作</label>
                </el-col>
              </el-row>
              <el-row :gutter="10" class="mb-10" type="flex" v-for="(d, i) in KpnInfo" :key="i">
                <el-col :span="4">
                  <el-select style="width: 100%" v-model="d.CurMaterialId" @change='changeMachine($event, d, i)'
                    filterable>
                    <el-option v-for="(i, t) in curRouteMaterialData" :key="t"
                      :label="`${i.name}/${data.ProductStuffix} `" :value="i.value"></el-option>
                  </el-select>
                </el-col>
                <el-col :span="14" class="ml-20">
                  <div class="flex gap-2 flex-wrap" style="flex-wrap:wrap">
                    <!-- <el-tag v-for="(ii,tt) in d.MachineCodes" @close="handleCloseMachineCode(d.MachineCodes,tt,ii)" closable class="m-5" :key='tt'
                        type="primary">{{
                        `名称：${ii.name} 数量：${ii.Qty}`
                        }}</el-tag> -->

                    <el-select style="width: 100%" v-model="d.MaterialId" multiple filterable>
                      <el-option v-for="(ii, tt) in d.MachineCodes" :key="tt" :label="`${ii.name} &nbsp; 数量：${ii.Qty} `"
                        :value='ii.value'></el-option>
                    </el-select>

                  </div>

                </el-col>

                <el-col :span="4">
                  <div class="flex">
                    <a class="text-red t-18 mt-8" type="text" @click.prevent="deleteSiteKpn(d, i)" circle><i
                        class="el-icon-delete"></i></a>
                    <a class="text-blue t-18 ml-12 mt-8" type="text" @click.prevent="addSiteKpn"
                      v-if="i == KpnInfo.length - 1" circle><i class="el-icon-circle-plus-outline"></i></a>
                  </div>
                </el-col>
              </el-row>
            </div>
            <div class="fr">
              <el-button type="primary" @click="submitKpn">保存物料信息</el-button>
            </div>
          </el-tab-pane>

        </el-tabs>
      </div>
    </div>

      <z-form-dialog :data="data" :formProps="formProps" :fields="fields" @submit="submit"
        :submitLoading="submitLoading" v-model="editFormVisible">
        <template v-slot:extra-area>
          <div >
            <el-tabs v-model="activeName" class="demo-tabs">
              <el-tab-pane label="设备信息维护" name="first">
                <div class="panel-body">
                  <el-row :gutter="10" type="flex" style="font-size: 12px; margin-bottom: 15px">
                    <el-col :span="4">
                      <label>设备</label>
                    </el-col>
                    <el-col :span="2">
                      <label>类型</label>
                    </el-col>
                    <el-col :span="3">
                      <label>UPH/时长(h)</label>
                    </el-col>
                    <el-col :span="3">
                      <label>产出节拍</label>
                    </el-col>
                    <el-col :span="3">
                      <label>前置时长</label>
                    </el-col>
                    <el-col :span="3">
                      <label>准备时长</label>
                    </el-col>
                    <el-col :span="3">
                      <label>后置时长</label>
                    </el-col>
                    <el-col :span="3">
                      <label>操作</label>
                    </el-col>
                  </el-row>
                  <el-row :gutter="10" class="mb-10" type="flex" v-for="(d, i) in MachineInfo" :key="i">
                    <el-col :span="4">
                      <el-select style="width: 100%" v-model="d.MachineId" filterable>
                        <el-option v-for="(i, t) in MachineOptions" :key="t"
                          :label="i.label" :value="i.MachineId"></el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="2">
                      <el-select style="width: 100%" v-model="d.Type" filterable>
                        <el-option label="UPH" value="1"></el-option>
                        <el-option label="固定时长(h)" value="2"></el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="3">
                      <el-input-number v-model="d.Uph"></el-input-number>
                    </el-col>
                    <el-col :span="3">
                      <el-input-number v-model="d.OutputCircle"></el-input-number>
                    </el-col>
                    <el-col :span="3">
                      <el-input-number v-model="d.BeforeMinutes"></el-input-number>
                    </el-col>
                    <el-col :span="3">
                      <el-input-number v-model="d.PreparationMinutes"></el-input-number>
                    </el-col>
                    <el-col :span="3">
                      <el-input-number v-model="d.AfterMinutes"></el-input-number>
                    </el-col>
                    <el-col :span="3">
                      <div class="flex">
                        <a class="text-red t-18 mt-8" type="text" @click.prevent="deleteSite(d, i)" circle><i
                            class="el-icon-delete"></i></a>
                        <a class="text-blue t-18 ml-12 mt-8" type="text" @click.prevent="addSite"
                          v-if="i == MachineInfo.length - 1" circle><i class="el-icon-circle-plus-outline"></i></a>
                      </div>
                    </el-col>
                  </el-row>
                </div>
                <div class="fr">
                  <el-button type="primary" @click="submit">保存设备信息</el-button>
                </div>
              </el-tab-pane>
              <el-tab-pane label="物料信息" name="second">
                <div class="panel-body">
                  <el-row :gutter="10" type="flex" style="font-size: 12px; margin-bottom: 15px">
                    <el-col :span="4">
                      <label>产品</label>
                    </el-col>
                    <el-col :span="14" class="ml-20">
                      <label>所需物料</label>
                    </el-col>
                    <el-col :span="4">
                      <label>操作</label>
                    </el-col>
                  </el-row>
                  <el-row :gutter="10" class="mb-10" type="flex" v-for="(d, i) in KpnInfo" :key="i">
                    <el-col :span="4">
                      <el-select style="width: 100%" v-model="d.CurMaterialId" @change='changeMachine($event,d,i)'
                        filterable>
                        <el-option v-for="(i, t) in curRouteMaterialData" :key="t"
                          :label="`${i.name}/${data.ProductStuffix} `" :value="i.value"></el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="14" class="ml-20">
                      <div class="flex gap-2 flex-wrap" style="flex-wrap:wrap">
                        <!-- <el-tag v-for="(ii,tt) in d.MachineCodes" @close="handleCloseMachineCode(d.MachineCodes,tt,ii)" closable class="m-5" :key='tt'
                        type="primary">{{
                        `名称：${ii.name} 数量：${ii.Qty}`
                        }}</el-tag> -->

                        <el-select style="width: 100%" v-model="d.MaterialId" multiple filterable>
                          <el-option v-for="(ii, tt) in d.MachineCodes" :key="tt"
                            :label="`${ii.name} &nbsp; 数量：${ii.Qty} `" :value='ii.value'></el-option>
                        </el-select>

                      </div>

                    </el-col>

                    <el-col :span="4">
                      <div class="flex">
                        <a class="text-red t-18 mt-8" type="text" @click.prevent="deleteSiteKpn(d, i)" circle><i
                            class="el-icon-delete"></i></a>
                        <a class="text-blue t-18 ml-12 mt-8" type="text" @click.prevent="addSiteKpn"
                          v-if="i == KpnInfo.length - 1" circle><i class="el-icon-circle-plus-outline"></i></a>
                      </div>
                    </el-col>
                  </el-row>
                </div>
                <div class="fr">
                  <el-button type="primary" @click="submitKpn">保存物料信息</el-button>
                </div>
              </el-tab-pane>

            </el-tabs>
          </div>
        </template>
      </z-form-dialog>
    </div>
</template>


<script setup>
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  CircleCloseFilled
} from '@element-plus/icons-vue'
</script>

<script>
import zFormDialog from '../../_common/formDialog.vue'
import _ from 'lodash'
export default {
  components: { zFormDialog },
  name: 'processPage',
  data() {
    return {
      activeName: "first",
      data: {},
      formProps: {
        dialogWidth: '99%',
        labelWidth: '120px',
        title: null, //dialog title
        hiddenButton: true,
      },
      MachineOptions: [],
      KpnOptions:[],
      items: [],
      MachineInfo: [{type:1}],
      KpnInfo: [{
        KpnOptions:[]
      }],
      canvasItems: [],
      curDragItem: {},
      draggedItem: null,
      connectorTop: 0,
      connectorLeft: 0,
      connectorWidth: 0,
      connectorHeight: 0,
      connectorAngle: 0,
      fields: [
        // { title: '产品后缀', key: 'ProductStuffix', span: 10 },
      ],
      editFormVisible: false,
      submitLoading: false,
      isAdd: false,
      initData: {},
      routeQuery:{},
      curCanvasItems: [],
      curMachineInfo: [], // 这个两个用于删除的时候比对 
      curRouteMaterialData:[], // 当前工艺的产品信息
      searchQuery: '', // 搜索框的值
      filteredItems: [], // 过滤后的列表
    };
  },
  watch:{
    $route:{
      handler(val, oldVal) {
        if(!!val.query.RouteNameId) {
          // 持久化储存
          localStorage.setItem('routeQuery', JSON.stringify(val.query))
          this.routeQuery = val.query
        }else {
          let routeQuery = JSON.parse(localStorage.getItem('routeQuery'))
          this.routeQuery = routeQuery

        }
      },
      immediate:true
    },
    // 监听 searchQuery 的变化
    searchQuery(newQuery) {
      this.filterItems();
    }
  },
  methods: {
    filterItems() {
      // 根据搜索框的值过滤列表
      if (this.searchQuery.trim() === '') {
        // 如果搜索框为空，显示所有内容
        this.filteredItems = this.items;
      } else {
        // 否则，根据搜索框的值过滤
        this.filteredItems = this.items.filter(item =>
          item.text.toLowerCase().includes(this.searchQuery.toLowerCase())
        );
      }
    },
    calCurItem(item) {
      return this.canvasItems.some(i => i.text === item.text)

    },
    handleCloseMachineCode(list,index,item){
      this.$confirm(`确定要去除当前物料：${item.name} 吗？`).then(() => {
        list.splice(index,1)
      })
    },
    changeMachine(v,item,index){
      this.http.post(this.$api.baseUrl + 'Aps_Bom/getPageData', { rows:99,wheres:JSON.stringify([
        {
          name:'ParentMaterialId',
          value:v
        }
      ]) }).then(r => {
        item.MachineCodes = r.rows.map(i => {
          return {
            ...i,
            value: i.MaterialId,
            name: `${i.MaterialInfo.MaterialCode} ${i.MaterialInfo.MaterialName}`
          }
        })
      })
    },

    deleteSite(item, index) {

      if (this.MachineInfo.length == 1) {
        this.MachineInfo = [{}]
      } else {

        this.MachineInfo.splice(index, 1)
      }
    },
    addSite() {

      this.MachineInfo.push({
      })
    },
    deleteSiteKpn(item, index) {

      if (this.KpnInfo.length == 1) {
        this.KpnInfo = [{}]
      } else {

        this.KpnInfo.splice(index, 1)
      }
    },
    addSiteKpn() {

    this.KpnInfo.push({

      })
    },
    submitKpn(){
      // 直接获取
      let KpnInfo = _.cloneDeep(this.KpnInfo)
      let list = KpnInfo.map(i => {
        i.MaterialIdData = i.MaterialId.map(ii => {
          return {
            MaterialId:ii,
            CurMaterialId: i.CurMaterialId,
            RouteControlId: this.curDragItem.RouteControlId,
            GroupId: this.curDragItem.CurrentGroupId,
            Qty: i.MachineCodes.find(j => j.value == ii)?.Qty
          }
        })

        return i.MaterialIdData.flat()
      }).flat()

      this.http.post('/api/Bas_RouteMaterial/AddRouteMaterial', list).then(r => {
        this.editFormVisible = false
        this.activeName = 'first'
      })
    },
    getGroupData() {
      this.http.post('/api/Bas_GroupConfig/GetPageData', { rows:999, order: 'asc', sort: 'GroupCode' }).then(r => {
        this.items = r.rows
        this.items.forEach(i => {
          i.text = i.GroupCode + " " + i.GroupName
        })
        //过滤数组赋值
        this.filteredItems = this.items
        this.getData()
      })
    },
    getMaterialData(){
      
      this.http.post('/api/Bas_RouteUsage/GetPageData', { wheres:JSON.stringify([
        {
          name:'RouteNameId',
          value:this.routeQuery.RouteNameId
        }
      ]) }).then(r => {
         r.rows.forEach(i => {
          i.value = i.Sku,
          i.name = `${i.MaterialInfo.MaterialCode} ${i.MaterialInfo.MaterialName}`
        })
        this.curRouteMaterialData = r.rows
        console.log(this.curRouteMaterialData,'this.curRouteMaterialData')

      })
    },
    handleDragStart(item) {
      let flag = this.canvasItems.some(i => i.text === item.text)
      if (flag) {
        return
      }
      this.draggedItem = item;
    },
    handleDragEnd() {
      this.draggedItem = null;
    },
    clickDragItem(item,index) {
      if (!item.RouteControlId) {
        this.$message.info("请先保存流程")
        return
      }
      
      this.MachineInfo = [{}]
      this.data = _.cloneDeep(this.initData)
      this.curDragItem = item
      this.editFormVisible = true
      this.activeName = 'first'

      this.http.post('/api/Bas_RouteDevice/getPageData', {
        sort: 'RouteDeviceId', wheres: JSON.stringify([
          {
            name: "RouteControlId",
            value: item.RouteControlId
          }
        ])
      }).then(r => {
        if (r.rows.length) {
          this.curMachineInfo = _.cloneDeep(r.rows)
          this.MachineInfo = r.rows
        }
        this.data.ProductStuffix = item.ProductStuffix
      })
      this.http.post('/api/Bas_RouteMaterial/getPageData', {
        sort: 'RouteDeviceId', wheres: JSON.stringify([
          {
            name: "RouteControlId",
            value: item.RouteControlId
          },
          {
            name:'GroupId',
            value: item.CurrentGroupId
          }
        ])
      }).then( r => {
        if(!r.rows.length) {
          this.KpnInfo = [{}]
          return 
        }
        let info = r.rows
        let KpnInfo = info.map((i,t) => {
          return {
            ...i,
            MaterialId: info.filter(j => j.CurMaterialId == i.CurMaterialId).map(k => k.MaterialId),
            MachineCodes: info.filter(j => j.CurMaterialId == i.CurMaterialId)
          }
        })
        // this.KpnInfo 根据 CurMaterialId 去重
        KpnInfo = KpnInfo.filter((item, index, arr) => {
          return arr.findIndex(i => i.CurMaterialId === item.CurMaterialId) === index
        })
        // 此处这样每次都需要更新select的options,后期考虑优化
        KpnInfo.map((i,t) => {
           this.changeMachine(i.CurMaterialId, i, t)
        })
        this.KpnInfo = KpnInfo
      })
    },
    delCur(index) {
      this.canvasItems.splice(index, 1)

    },

    getMachineOptions() {

      this.http.post(this.$api.machine + 'GetPageData', {
        rows: 999,
      }).then((r) => {
        this.MachineOptions = r.rows.filter(i => i.Level != null)
        this.MachineOptions.forEach(i => {
          i.label = `${i.MachineCode} ${i.MachineName}`
          // i.label = `${i.MachineCode} ${i.MachineName} ${i.RelatedDevice ? '_关联设备：' + i.RelatedDeviceInfo.MachineCode + ' ' + i.RelatedDeviceInfo.MachineName + '，' : ''} ${i.IsCe ? '_含Ce' + '，' : ''} ${i.PositionRow ? '_位置：' + i.PositionRow + '，' : ''}`
        })
      })


    },

    getKpnOptions(v ) {

      this.http.post(this.$api.material + 'GetPageData', {
        rows: 9999,
        wheres:v?JSON.stringify([
          {
            name:'queryCodeName',
            value:v
          }
        ]):"[]"
      }).then((r) => {
        this.KpnOptions = r.rows

      })
    },
    submit() {
      // this.http.post(this.$api.baseUrl + 'Bas_RouteControl/update', { mainData: { ...this.curDragItem, ProductStuffix: this.data.ProductStuffix } }).then(r => {
      // })


      // let url = this.isAdd ? 'Bas_RouteControl/add' : 'Bas_RouteControl/update'
      let url = 'Bas_RouteControl/update'
      let data = {
        mainData: {
          ...this.curDragItem,
          ProductStuffix: this.data.ProductStuffix,
        },
        delKeys: _.differenceWith(this.curMachineInfo, this.MachineInfo, (objA, objB) => objA.RouteDeviceId === objB.RouteDeviceId).map(i => i.RouteDeviceId),
        detailData: this.MachineInfo.map((i, index) => {
          let tmp = this.MachineOptions.find(j => j.MachineId == i.MachineId)
          return {
            ...i,
            RouteControlId: this.curDragItem.RouteControlId,
            GroupId: this.curDragItem.CurrentGroupId,
            IsCe: tmp?.IsCe,
            RelatedDevice: tmp?.RelatedDevice,
            PositionRow: tmp?.PositionRow,
          }
        })

      }
      this.http.post(this.$api.baseUrl + url, { ...data }, '', { noMessage: true }).then(r => {
        this.editFormVisible = false
        this.getData()

      })
    },
    tranText(id) {
      let tmp = this.items.find(i => i.GroupId == id)
      if (!!tmp) {
        return tmp.text
      }
      return ''
    },
    getData() {
      this.canvasItems = []
      this.curDragItem = {}

      this.http.post(this.$api.baseUrl + 'Bas_RouteControl/getPageData', {
        rows: 999,
        sort: 'StepSequence',
        order: 'asc',
        wheres: JSON.stringify([
          {
            name: "RouteNameId",
            value: this.routeQuery.RouteNameId
          }
        ])
      }).then((r) => {
        r.rows.forEach(i => {
          i.text = this.tranText(i.CurrentGroupId)
        })
        this.curCanvasItems = _.cloneDeep(r.rows)
        this.canvasItems = r.rows
        console.log(this.canvasItems, 'this.canvasItems')
      })
    },
    handleDrop(event) {
      if (!this.draggedItem) return;

      this.$nextTick(() => {

        const canvasRect = this.$refs.canvas.getBoundingClientRect();
        const mouseX = event.clientX - canvasRect.left;
        const mouseY = event.clientY;

        let insertIndex = -1;
        for (let i = 0; i < this.canvasItems.length; i++) {
          const itemRect = this.$refs.canvas.querySelector(`[data-index="${i}"]`);
          console.log("🚀 ~ this.$nextTick ~ itemRect:", itemRect)
          if (itemRect) {
            const rect = itemRect.getBoundingClientRect();

            if (mouseY + rect.height >= rect.top && mouseY <= rect.bottom + 10) {

              // 假设在元素上方或下方10px内都视为间隙
              if (i === 0 || mouseY <= rect.top) {
                // 插入到当前元素之前
                insertIndex = i;
              } else {
                // 插入到当前元素之后
                insertIndex = i + 1;
              }
              break;
            }
          }
        }
        if (insertIndex !== -1) {
          const newItem = { ...this.draggedItem };
          this.canvasItems.splice(insertIndex, 0, newItem);

          // 如果是第一个元素，标记为开始元素
          if (this.canvasItems.length === 1) {
            this.canvasItems[0].isStart = true;
          }

          // 重置 draggedItem
          this.draggedItem = null;
        } else {
          const newItem = { ...this.draggedItem };
          this.canvasItems.push(newItem);
        }

      })

    },
    handleClickCanvas() {
      if (this.canvasItems.length) {
        const lastItem = this.canvasItems[this.canvasItems.length - 1];
      }
    },
    saveData() {

      let url = 'Bas_RouteName/update'
      let data = {
        mainData: {
          RouteNameId: this.routeQuery.RouteNameId,
          RouteName: this.routeQuery.RouteName,
          RouteCode: this.routeQuery.RouteCode,
        },
        details: [
          {
            data: this.canvasItems.map((i, index) => {
              return {
                ...i,
                StepSequence: index + 1,
                RouteNameId: this.routeQuery.RouteNameId,
                CurrentGroupId: i.GroupId,

              }
            }),
            table: "Bas_RouteControl",
            delKeys: _.differenceWith(this.curCanvasItems, this.canvasItems, (objA, objB) => objA.RouteControlId === objB.RouteControlId).map(i => i.RouteControlId),
          }
        ],
      }

      this.http.post(this.$api.baseUrl + url, { ...data }, '', { noMessage: true }).then(r => {
        this.$message.success('保存成功')
        this.getData()
      })


    },
  },
  mounted() {
    this.getGroupData()
    this.getMachineOptions()
    this.getKpnOptions()
    this.getMaterialData()
  }
};
</script>

<style lang="scss" scoped>
.drag-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  border-right: 1px solid #ccc
}
.topTitle {
  border: 1px solid #e4e4e4;
  padding: 38px 10px 10px;
  position: relative;
}

.topTitle .top-title {
  transition: all 0.5s;
  color: #666;
  background: #f1f1f1;
  height: 28px;
  line-height: 28px;
  position: absolute;
  width: 100%;
  left: -10px;
  font-size: 12px;
  font-weight: 500;
  padding-left: 20px;
  top: 0;
  left: 0;
  // letter-spacing: 2px;
  z-index: 9;
}
.top-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 10px;
}

.draggable-item {
  cursor: move;
  padding: 10px;
  margin: 5px;
  background-color: lightblue;
  border-radius: 5px;
  width: 160px;
  height: 40px;
}

.disabledItem {
  background-color: rgba(178, 184, 186, 0.571);
}

.canvas {
  position: relative;
  /* border: 1px solid #ccc; */
  padding: 10px;
  min-height: 300px;
  text-align: center;
  display: flex;
  align-items: center;
  flex-direction: column;
}

.canvas-item {
  cursor: pointer;
  width: 200px;
  height: 60px;
  line-height: 60px;
  margin: 5px;
  color: #333;
  border: 2px solid #333;
  /* background-color: lightgreen; */
  border-radius: 5px;
  position: relative;
  margin-bottom: 50px;
  /* position: absolute; */
}

.start {
  color: #7300E6;
  border: 2px solid #7300E6;
}

.end {
  color: #7300E6;
  border: 2px solid #7300E6;
}

.delBtn {
  cursor: pointer;
  width: 30px;
  height: 30px;
  line-height: 30px;
  border-radius: 50%;
  /* background-color: rgba(255, 0, 0, 0.568); */
  position: absolute;
  top: -10px;
  right: -10px;
}

.divText {
  position: absolute;
  bottom: -20px;
  right: 1px;
  color: #7300E6;
  font-size: 12px;
}

/* 连线样式 */
.connector {
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 0;
  background-color: black;
  transform-origin: left center;
}

/* 箭头样式 */
.arrow {
  content: '';
  position: absolute;
  right: -9px;
  top: 40px;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 10px solid transparent;
  border-top: 10px solid black;
}

.list-container {
  height: 600px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.canvas-container {
  height: 650px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>